package org.rency.mq.activemq.listener.failover.impl;

import com.alibaba.fastjson.JSON;
import org.rency.mq.activemq.constant.DeliveryMode;
import org.rency.mq.activemq.constant.DestinationType;
import org.rency.mq.activemq.constant.MessageFormat;
import org.rency.mq.activemq.jms.service.JmsAccessor;
import org.rency.mq.activemq.request.MQRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.JMSException;
import javax.jms.Session;
import java.util.Map;

public class RetryTask implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(RetryTask.class);
    private JmsAccessor mqAccessor;
    private MQRequest request;

    public RetryTask(JmsAccessor mqAccessor, MQRequest request) {
        this.mqAccessor = mqAccessor;
        this.request = request;
    }

    public void run() {
        logger.info("Retry to send MQRequest to original queue: " + request.toString());

        try {
            mqAccessor.sendMessage(request.getDestination(), request.getDestinationType(),
                request.getMessageFormat(), request.isTransacted(), request.getAcknowledgeMode(),
                request.getDeliveryMode(), request);
        } catch (JMSException e) {
            logger.error("Fail to send message to original queue:" + request.getDestination() + "", e);
            Map<String, Object> props = request.getProperties();

            try {
                Boolean isSendToFail = (Boolean) props.get("isSendToFail");
                if (isSendToFail != null && isSendToFail) {
                    mqAccessor.sendMessage((String) props.get("failedQueue"),
                        DestinationType.QUEUE, MessageFormat.OBJECT, false,
                        Session.AUTO_ACKNOWLEDGE, DeliveryMode.PERSISTENT,JSON.toJSONString(request));
                } else {
                    logger.warn("没有配置发送到失败队列.消息将被丢弃.message:" + request.toString());
                }
            } catch (JMSException ex) {
                logger.error("Send message to failed queue:" + (String) props.get("failedQueue")+ " failed.", ex);
            }
        }
    }

}
